package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.dto.ArticleDto;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entily.WmChannel;
import com.heima.media.entily.WmSensitive;
import com.heima.media.entily.WmUser;
import com.heima.media.entity.WmNews;
import com.heima.media.feign.ArticleFeign;
import com.heima.media.service.*;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RBatch;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: heima-leadnews
 * @BelongsPackage: com.heima.media.service.impl
 * @Author: wangjian
 * @CreateTime: 2022-07-02  18:52
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class AuditServiceImpl  implements IAuditService {
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    @Lazy
    private IWmNewsService wmNewsService;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IWmUserService wmUserService;
    @Autowired
    private IWmChannelService channelService;
    @Autowired
    private RedissonClient redissonClient;







    @Override
    @Async
    public void audit(Integer id) {
        WmNews wmNews= wmNewsService.getById(id);
        audit(wmNews);

    }
    @Override
    @Async
    public void audit(WmNews wmNews) {
            //先进行敏感词判断 省钱 !!
            boolean isPass = checkSensitive(wmNews);
              if (!isPass) return;
//            阿里云文本审核
            isPass = checkText(wmNews);
            if (!isPass) return;
//       阿里云的图片审核
            isPass = checkImage(wmNews);
            if (!isPass) return;
//       保存app的文章
//        判断现在的时间是不是已经到达了发布时间
            if (System.currentTimeMillis() >= wmNews.getPublishTime().getTime()) {
                Long articleId = saveArticle(wmNews);
                wmNews.setArticleId(articleId);
                wmNews.setStatus(9);
            } else {

                //没有到发布时间
                RBlockingDeque<Object> articleBqueue = redissonClient.getBlockingDeque("article_bqueue");
                RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(articleBqueue);
                //设置预期发布
                Long time= wmNews.getPublishTime().getTime()-System.currentTimeMillis();
                   delayedQueue.offer(wmNews.getId(),time, TimeUnit.MICROSECONDS);
                wmNews.setStatus(8);
            }
            wmNewsService.updateById(wmNews);
        }


    //    根据wmNews 构建ArticleDto
    public  Long saveArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setId(null);
//        app用户可以申请成自媒体用户,自媒体用户自动就是文章作者
//        获取自媒体用户，自媒体用户中有AuthorId
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wmUserService.getById(userId);
        articleDto.setAuthorId(wmUser.getApAuthorId());
        articleDto.setAuthorName(wmUser.getName());
        articleDto.setChannelId(wmNews.getChannelId());
        WmChannel wmChannel = channelService.getById(wmNews.getChannelId());
        articleDto.setChannelName(wmChannel.getName());
        articleDto.setLayout(wmNews.getType());
        articleDto.setFlag(0); //平台文章
        List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
        List<String> urlList = new ArrayList<>();
        for (ImageDto imageDto : imageDtoList) {
            urlList.add(imageDto.getUrl());
        }
        articleDto.setImages(JSON.toJSONString(urlList)); // 格式不一样
        ResponseResult<Long> longResponseResult = articleFeign.saveArticle(articleDto);
        Long articleId = longResponseResult.getData();
        return articleId;
    }
    private boolean checkText(WmNews wmNews) {
//        文本包括：文章标题+文章的内容
        String text =  wmNews.getTitle();
        List<ContentDto> contentDtos =  JSON.parseArray(wmNews.getContent(), ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("text")) {
                text += contentDto.getValue();
            }
        }

        boolean isPass = false;
        try {
//            suggestion
//            pass：文本正常，可以直接放行。
//            review：文本需要进一步人工审核。             label=porn
//            block：文本违规，可以直接删除或者限制公开。  label=porn
            Map map = greenTextScan.greenTextScan(text);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "pass":
                    isPass = true;
                    break;
                case "review":
                    wmNews.setStatus(3);
                    wmNews.setReason("阿里云文本审核未通过，需要人工审核，原因是：" + map.get("label")); //审核不通过或需要人工审核的原因
                    wmNewsService.updateById(wmNews);
                    isPass = false;
                    break;
                case "block":
                    wmNews.setStatus(2);
                    wmNews.setReason("阿里云文本审核未通过，原因是：" + map.get("label")); //审核不通过或需要人工审核的原因
                    wmNewsService.updateById(wmNews);
                    isPass = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isPass;
    }
    private boolean checkImage(WmNews wmNews) {
        boolean isPass = false;
        String coverImages =  wmNews.getImages(); //获取封面图片
        List<ImageDto> imageDtoList = JSON.parseArray(coverImages, ImageDto.class);
        List<ContentDto> contentDtos =  JSON.parseArray(wmNews.getContent(), ContentDto.class);
        for (ContentDto contentDto : contentDtos) {  //需要把内容图片放到imageDtoList中
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                if(!imageDtoList.contains(imageDto)){ //判断是否有重复的，如果有就不再放入了
                    imageDtoList.add(imageDto);
                }
            }
        }

        try {
            //        现在的imageDtoList就是封面图片+内容图片
            List<byte[]> imageList = new ArrayList<>();
//        把图片都转成字节数组
            for (ImageDto imageDto : imageDtoList) {
                InputStream inputStream = minIOService.download(imageDto.getUrl());
                byte[] bytes = IOUtils.toByteArray(inputStream);
                imageList.add(bytes);
            }
//            suggestion
//            pass：文本正常，可以直接放行。
//            review：文本需要进一步人工审核。
//            block：文本违规，可以直接删除或者限制公开。
            Map map = greenImageScan.imageScan(imageList);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "pass":
                    isPass = true;
                    break;
                case "review":
                    wmNews.setStatus(3);
                    wmNews.setReason("阿里云图片审核未通过，需要人工审核，原因是：" + map.get("label")); //审核不通过或需要人工审核的原因
                    wmNewsService.updateById(wmNews);
                    isPass = false;
                    break;
                case "block":
                    wmNews.setStatus(2);
                    wmNews.setReason("阿里云图片审核未通过，原因是：" + map.get("label")); //审核不通过或需要人工审核的原因
                    wmNewsService.updateById(wmNews);
                    isPass = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isPass;
    }
    @Autowired
    private IWmSensitiveService sensitiveService;

    private boolean checkSensitive(WmNews wmNews) {
        String text =  wmNews.getTitle();
        //        从Content中提取文本
        List<ContentDto> contentDtos =  JSON.parseArray(wmNews.getContent(), ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("text")) {
                text += contentDto.getValue();
            }
        }

        //        构建一个DFA算法的Map
        List<WmSensitive> list = sensitiveService.list();
        List<String> sensitiveWords = new ArrayList<>();
        for (WmSensitive sensitive : list) {
            sensitiveWords.add( sensitive.getSensitives());
        }
        SensitiveWordUtil.initMap(sensitiveWords);
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(text);
        //        stringIntegerMap = {小额贷款=1, 随机随贷=1, 无抵押=2}
        if(stringIntegerMap.size()>0){ //表示内容中有敏感词 不通过的
            Set<String> strings = stringIntegerMap.keySet();
            String reason = String.join(",", strings); //把key的set集合转成字符串
            wmNews.setStatus(2);
            wmNews.setReason("敏感词审核未通过，原因是包含以下敏感词：" +reason); //审核不通过或需要人工审核的原因
            wmNewsService.updateById(wmNews);
            return false;
        }else{
            return true;
        }
}
}
